package com.zzh.wechatpay.intercepter;

import com.google.gson.Gson;
import com.zzh.wechatpay.domain.JsonData;
import com.zzh.wechatpay.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zzh
 * @date 2019/11/26
 * @description 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Gson gson = new Gson();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            token=request.getParameter("token");
        }
        if (token != null) {
            Claims claims = JwtUtils.checkJWT(token);
            Integer id = (Integer) claims.get("id");
            String name = (String) claims.get("name");
            request.setAttribute("id",id);
            request.setAttribute("name",name);
            return true;
        }
        sendJsonMessage(response,gson.toJson(JsonData.buildError("请登录")));
        return false;
    }
    /**
     * 响应数据给前端
     * @param response
     * @param obj
     */
    private static void sendJsonMessage(HttpServletResponse response, Object obj) throws IOException {

        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(gson.toJson(obj));
        writer.close();

        response.flushBuffer();

    }
}
